import 'package:flutter/material.dart';
import 'package:htxd_flutter_mapbox_sdk/htxd_flutter_mapbox_sdk.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';

/// 地图加载 失败
typedef MapLoadFailed = Function(String message);

/// 地图加载 成功
typedef MapLoadSuccess = Function(MapBoxControl mapBoxControl);

/// baseMapView 将基本功能封装到里面
class BaseMapView extends StatelessWidget {
  final MapLoadFailed? mapLoadFailed;
  final MapLoadSuccess? mapLoadSuccess;
  final OnMapLongTapListener? onMapLongTapListener;
  final OnMapTapListener? onMapTapListener;
  final OnMapScrollListener? onMapScrollListener;
  final OnCameraChangeListener? onCameraChangeListener;

  /// 是否直接定位
  bool isStartLocation;
  bool isHideScaleBar;
  BaseMapView(
      {Key? key,
      this.mapLoadFailed,
      this.mapLoadSuccess,
      this.isStartLocation = false,
      this.isHideScaleBar = true,
      this.onMapTapListener,
      this.onMapLongTapListener,
      this.onMapScrollListener,
      this.onCameraChangeListener})
      : super(key: key);

  MapBoxControl? _mapBoxControl;

  MapboxMap? _mapboxMap;

  @override
  Widget build(BuildContext context) {
    return MapWidget(
      resourceOptions: ResourceOptions(accessToken: Contract.MAP_BOX_KEY),
      styleUri: MapboxStyles.SATELLITE,
      onMapLoadErrorListener:
          (MapLoadingErrorEventData mapLoadingErrorEventData) {
        if (mapLoadFailed != null) {
          mapLoadFailed!(mapLoadingErrorEventData.message);
        }
      },
      onMapCreated: (MapboxMap control) {
        _mapboxMap = control;
      },
      onStyleLoadedListener: (styleLoadedEventData) {
        _mapBoxControl = MapBoxControl(_mapboxMap!);
        if (mapLoadSuccess != null) {
          mapLoadSuccess!(_mapBoxControl!);
        }
        _loadMapSuccess();
      },
      onLongTapListener: (coordinate) {
        if (onMapLongTapListener != null) {
          onMapLongTapListener!(coordinate);
        }
      },
      onTapListener: (coordinate) {
        if (onMapTapListener != null) {
          onMapTapListener!(coordinate);
        }
      },
      onScrollListener: (coordinate) {
        if (onMapScrollListener != null) {
          onMapScrollListener!(coordinate);
        }
      },
      onCameraChangeListener: (cameraChangedEventData) {
        onCameraChangeListener?.call(cameraChangedEventData);
      },
    );
  }

  // 地图加载成功执行的操作
  void _loadMapSuccess() {
    _mapBoxControl?.hideMapLogo(isHideScaleBar);
    if (isStartLocation) {
      _mapBoxControl?.startLocation();
    }
  }
}
